package com.cch.stock.set.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.cch.platform.util.DateUtil;
import com.cch.stock.set.bean.SdStock;
import com.cch.stock.set.bean.SdStockDaliy;
import com.cch.stock.set.dao.StockDao;
import com.cch.stock.set.dao.StockPriceDao;

@Service
public class StockPriceService {
	
	@Autowired
	StockPriceDao spDao;

	@Autowired
	StockDao stockDao;
	
	public void updatePrice(String stockCode, Date from, Date to){
		SdStock stock = stockDao.get(stockCode);
		Assert.notNull(stock);
		Assert.notNull(from);
		Assert.notNull(to);
		
		GetDataFromYahoo yahoo=new GetDataFromYahoo();
		List<SdStockDaliy> listd=yahoo.getStockCsvData(stock, from, to);
		for(SdStockDaliy one:listd){
			spDao.saveOrUpdate(one);
		}
	}
	
	public SdStockDaliy  getPrice(String stockCode,Date date){
		Date openDay=DateUtil.getOpenDay(date, false);
		SdStockDaliy stockPrice=new SdStockDaliy(stockCode,openDay);
		stockPrice=spDao.get(stockPrice);
		if(stockPrice==null){
			stockPrice=this.getPriceOut(stockCode, openDay);
		}
		return stockPrice;
	}

	public Map<String, Object> pageQuery(Map<String, Object> param) {
		return spDao.pageQuery(param);
	}
	
	private SdStockDaliy getPriceOut(String stockCode,Date date){
		Calendar calDay=Calendar.getInstance();
		calDay.setTime(date);
		calDay.add(Calendar.DATE, 14);
		this.updatePrice(stockCode, date, calDay.getTime());
		SdStockDaliy stockPrice=new SdStockDaliy(stockCode,date);
		SdStockDaliy stockPrice1=spDao.get(stockPrice);
		if(stockPrice1==null){
			stockPrice.setPriceClose(0.0);
			stockPrice.setPriceOpen(0.0);
			stockPrice.setPriceHigh(0.0);
			stockPrice.setpriceLow(0.0);
			spDao.save(stockPrice);
			return stockPrice;
		}
		return stockPrice1;
	}
	
}